<!-- src/components/Task/TaskCardList.vue -->
<template>
  <main class="task-main" ref="taskMainRef">
    <div class="task-cards-container" ref="taskCardsContainer">
      <div class="task-cards-scroll" ref="cardsScroll" @click="handleContainerClick">
        <div
            class="task-card-wrapper"
            v-for="(list, listIndex) in taskLists"
            :key="list.id"
            :style="getCardWrapperStyle(listIndex)"
            :ref="(el) => setCardWrapperRef(el, listIndex)"
        >
          <TaskCard
              :active-calendar-task-id="activeCalendarTaskId"
              @set-active-calendar="(taskId) => emit('set-active-calendar', taskId)"
              :task-list="list"
              :list-index="listIndex"
              :active="activeListIndex === listIndex"
              :max-card-height="maxCardHeight"
              :card-fixed-height="cardFixedHeight"
              :tasks-list-padding="tasksListPadding"
              :tasks-list-gap="tasksListGap"
              @click="() => emit('handle-card-click', listIndex)"
              @add-task="() => emit('add-task-to-list', listIndex)"
              @start-editing-name="() => emit('start-editing-list-name', listIndex)"
              @save-name="(newName: string) => emit('save-list-name', listIndex, newName)"
              @show-options-menu="() => emit('show-list-options-menu', listIndex)"
              @task-complete="(listIndex, taskIndex, completed) => emit('handle-task-complete', listIndex, taskIndex, completed)"
              @start-editing="(payload) => emit('start-editing', listIndex, payload.taskIndex, payload.type, payload.event)"
              @save-editing="(payload) => emit('save-editing', listIndex, payload.taskIndex, payload.type, payload.event)"
              @title-enter="taskIndex => emit('handle-title-enter', listIndex, taskIndex)"
              @navigate-to-desc="taskIndex => emit('navigate-to-desc', listIndex, taskIndex)"
              @navigate-to-title="taskIndex => emit('navigate-to-title', listIndex, taskIndex)"
              @set-date="({ taskIndex, date }) => emit('set-task-date', listIndex, taskIndex, date)"
              @toggle-options="({ taskIndex, event }) => emit('toggle-task-options', listIndex, taskIndex, event)"
              @delete-task="taskIndex => emit('delete-task', listIndex, taskIndex)"
              @delete-card="() => emit('delete-card', listIndex)"
              @move-card="() => emit('move-card', listIndex)"
              @update-show-date-mode="(taskIndex: number, showAsText: boolean) => emit('update-task-show-date-mode', listIndex, taskIndex, showAsText)"
          />
        </div>
      </div>
    </div>
  </main>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue'
import type { ComponentPublicInstance } from 'vue'
import TaskCard from './TaskCard.vue'
import type { TaskList } from '@/types/taskList'

const props = defineProps<{
  activeCalendarTaskId: string | null
  taskLists: TaskList[]
  activeListIndex: number
  showTaskOptions: boolean
}>()

const emit = defineEmits<{
  (e: 'handle-card-click', index: number): void
  (e: 'add-task-to-list', index: number): void
  (e: 'start-editing-list-name', index: number): void
  (e: 'save-list-name', listIndex: number, newName: string): void
  (e: 'show-list-options-menu', index: number): void
  (e: 'handle-task-complete', listIndex: number, taskIndex: number, completed: boolean): void
  (e: 'start-editing', listIndex: number, taskIndex: number, type: 'title' | 'desc', event: Event): void
  (e: 'save-editing', listIndex: number, taskIndex: number, type: 'title' | 'desc', event: Event): void
  (e: 'handle-title-enter', listIndex: number, taskIndex: number): void
  (e: 'navigate-to-desc', listIndex: number, taskIndex: number): void
  (e: 'navigate-to-title', listIndex: number, taskIndex: number): void
  (e: 'set-task-date', listIndex: number, taskIndex: number, date: 'today' | 'tomorrow' | string): void
  (e: 'toggle-task-options', listIndex: number, taskIndex: number, event: MouseEvent): void
  (e: 'delete-task', listIndex: number, taskIndex: number): void
  (e: 'update:show-task-options', val: boolean): void
  (e: 'set-active-calendar', taskId: string | null): void
  (e: 'delete-card', listIndex: number): void
  (e: 'move-card', listIndex: number): void
  (e: 'clear-active-card'): void
  (e: 'update-task-show-date-mode', listIndex: number, taskIndex: number, showAsText: boolean): void
}>()

const taskMainRef = ref<HTMLDivElement | null>(null)
const cardsScroll = ref<HTMLDivElement | null>(null)
const cardWrappers = ref<(HTMLDivElement | null)[]>([])
const taskCardsContainer = ref<HTMLDivElement | null>(null)
const maxCardHeight = ref<number>(0)

const horizontalScrollSpeed = 30
const verticalScrollSpeed = 10
const cardWidth = 450
const cardGap = 20
const scrollSpeed = 15
const headerHeight = 100
const footerHeight = 5
const cardFixedHeight = headerHeight + footerHeight
const tasksListPadding = 40
const tasksListGap = 12

const calculateMaxCardHeight = () => {
  if (taskMainRef.value) {
    // 计算父容器高度的 80% 作为卡片最大高度
    const parentHeight = taskMainRef.value.clientHeight;
    maxCardHeight.value = parentHeight * 0.6; // 60% 高度
  }
};

const handleContainerClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement
  // 检查点击是否落在任意 .task-card 内部
  if (!target.closest('.task-card')) {
    emit('clear-active-card')
  }
}

// 获取卡片包装器样式
const getCardWrapperStyle = (listIndex: number) => {
  let hiddenWidth = 0;
  for (let i = 0; i < listIndex; i++) {
    const taskList = props.taskLists[i];
    // 关键：只要卡片处于隐藏状态（包括动画中），就计算其宽度，触发右侧移动
    if (taskList && !taskList.visible) {
      hiddenWidth += cardWidth + cardGap; // 累加隐藏卡片的宽度+间距
    }
  }
  return {
    transform: `translateX(-${hiddenWidth}px)`, // 右侧卡片左移的距离
    width: `${cardWidth}px`,
    marginRight: `${cardGap}px`,
    flexShrink: '0'
  };
};

const setCardWrapperRef = (el: Element | ComponentPublicInstance | null, index: number) => {
  cardWrappers.value[index] = el instanceof HTMLElement ? el as HTMLDivElement : null
}

const handleWheel = (e: WheelEvent) => {
  // 1. 有选中的卡片时，纵向滚动（低灵敏度）
  if (props.activeListIndex !== -1) {
    e.preventDefault();

    const activeCard = cardWrappers.value[props.activeListIndex];
    const cardBody = activeCard?.querySelector('.card-body') as HTMLElement;

    if (cardBody) {
      // 使用纵向滚动速度（较慢）
      cardBody.scrollTop += e.deltaY * (verticalScrollSpeed / 15); // 基准值15做比例计算
      return;
    }
  }

  // 2. 无选中卡片时，横向滚动（高灵敏度）
  if (cardsScroll.value) {
    e.preventDefault();
    cardsScroll.value.style.scrollBehavior = 'auto';
    // 使用横向滚动速度（较快）
    cardsScroll.value.scrollLeft += e.deltaY > 0 ? horizontalScrollSpeed : -horizontalScrollSpeed;
    setTimeout(() => {
      if (cardsScroll.value) {
        cardsScroll.value.style.scrollBehavior = 'smooth';
      }
    }, 50);
  }
}

// 滚动到新列表
const scrollToNewList = (index: number) => {
  nextTick(() => {
    const scrollContainer = cardsScroll.value
    const cardWrapper = cardWrappers.value[index]
    if (scrollContainer && cardWrapper) {
      const containerRect = scrollContainer.getBoundingClientRect()
      const cardRect = cardWrapper.getBoundingClientRect()
      const scrollLeft = cardRect.left - containerRect.left + scrollContainer.scrollLeft
      scrollWithAnimation(scrollContainer, scrollLeft, 300)
    }
  })
}

const scrollToCard = (index: number) => {
  nextTick(() => {
    const scrollContainer = cardsScroll.value
    const cardWrapper = cardWrappers.value[index]
    if (scrollContainer && cardWrapper) {
      const containerRect = scrollContainer.getBoundingClientRect()
      const cardRect = cardWrapper.getBoundingClientRect()
      const scrollLeft = cardRect.left - containerRect.left + scrollContainer.scrollLeft
      scrollWithAnimation(scrollContainer, scrollLeft, 300)
    }
  })
}

const scrollWithAnimation = (element: HTMLElement, targetPosition: number, duration: number) => {
  const startPosition = element.scrollLeft
  const distance = targetPosition - startPosition
  const startTime = performance.now()
  const easeOutQuad = (t: number) => t * (2 - t)
  const animateScroll = (currentTime: number) => {
    const timeElapsed = currentTime - startTime
    const progress = Math.min(timeElapsed / duration, 1)
    const easedProgress = easeOutQuad(progress)
    element.scrollLeft = startPosition + distance * easedProgress
    if (progress < 1) requestAnimationFrame(animateScroll)
  }
  requestAnimationFrame(animateScroll)
}


onMounted(() => {
  calculateMaxCardHeight()
  window.addEventListener('resize', calculateMaxCardHeight)
  // 给容器添加滚轮事件监听
  window.addEventListener('wheel', handleWheel, { passive: false })
})

onUnmounted(() => {
  window.removeEventListener('resize', calculateMaxCardHeight)
  window.removeEventListener('wheel', handleWheel)
})

watch(
    () => props.activeListIndex,
    (newIndex) => {
      // 仅当 newIndex 不是 -1 时才滚动（删除后 newIndex 为 -1，不滚动）
      if (newIndex !== -1) {
        scrollToCard(newIndex)
      }
    },
    { immediate: true }
)

// 监听任务列表长度变化
watch(
    () => props.taskLists.length,
    (newLength, oldLength) => {
      if (newLength > oldLength) {
        // 新列表创建后自动滚动到该列表
        scrollToNewList(newLength - 1)
      }
    }
)
</script>

<style scoped>
.task-main {
  flex: 1;
  padding: 32px;
  overflow: hidden;
  background: #f5f7fa;
  height: 100%;
  box-sizing: border-box;
}

.task-cards-container {
  width: 100%;
  overflow: hidden;
  height: 100%;
}

.task-cards-scroll {
  display: flex;
  padding: 0;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  scroll-behavior: smooth;
  height: 100%;
}

.task-cards-scroll::-webkit-scrollbar {
  display: none;
}

.task-card-wrapper {
  display: block;
  flex-shrink: 0;
  margin-top: 10px;
  height: v-bind(maxCardHeight);
}

.task-card-wrapper:last-child {
  margin-right: 0 !important;
}
</style>